<!-- aillo 主页-->

<template>
  <div
    class="aillo-home"
    v-loading="loading"
    element-loading-text="数据加载中"
    element-loading-spinner="el-icon-loading"
  >
    <!--   ------------- 左侧菜单 开始 ------------- -->
    <div class="menu">
      <div class="menu__title">
        <el-popover placement="right" width="237" trigger="click">
          <div class="user-info-card">
            <el-avatar :size="40" :src="avatar">
              <img src="../assets/picture/defaultAvatar.png" />
            </el-avatar>
            <div class="user-info-card__info">
              <span class="user-info-card__info__name">
                {{ username ? username : "" }}
                <i
                  v-if="sex === 1"
                  class="tico tico-female user-info-card__info__female"
                />
                <i v-else class="tico tico-male user-info-card__info__male" />
              </span>
              <span class="user-info-card__info__account"
                >账号&nbsp;{{ userNumber || "" }}</span
              >
              <span class="user-info-card__info__district"
                >ID&nbsp;{{ uId || "" }}</span
              >
            </div>
          </div>
          <!-- <Avatar slot="reference" class="menu__title__avatar" :src="avatar" /> -->
          <el-avatar
            :size="40"
            :src="avatar"
            slot="reference"
            class="menu__title__avatar"
          >
            <img src="../assets/picture/defaultAvatar.png" />
          </el-avatar>
        </el-popover>
      </div>

      <!-- 聊天组件 -->
      <el-badge :hidden="uneradNum === 0" :value="uneradNum" class="menu__chat">
        <i
          class="tico tico-daohanglan-xiaoxi menu__chat__icon"
          @click="changeChatListVisible(true)"
          :style="chatIcon"
        />
      </el-badge>

      <!-- 好友群组 组件-->
      <el-badge class="menu__user">
        <i
          class="tico tico-daohanglan-lianxiren menu__chat__icon"
          @click="changeChatListVisible(false)"
          :style="userIcon"
        />
      </el-badge>
      <!-- <Popover trigger="click" placement="right-end" width="150px" :visible-arrow="false">
        <div class="chat-list-setting-popover">
          <span @click="notificationVisible = true">通知</span>
          <span>存储</span>
          <span @click="feedbackVisible = true">问题反馈</span>
          <span>退出登录</span>
        </div>
        <img slot="reference" class="menu__setting" src="../assets/picture/setting.png" />
      </Popover>-->
      <img
        class="menu__setting"
        @click="logOut()"
        src="../assets/svg/log-out.svg"
      />
    </div>
    <!--   ------------- 左侧菜单 结束 ------------- -->

    <div class="chat-list">
      <div class="chat-list__title">
        <el-input
          v-show="chatListVisible"
          clearable
          class="chat-list__title__search"
          placeholder="搜索..."
          v-model="search"
        >
          <img slot="prefix" src="../assets/picture/iconfont-sousuo@2x.png" />
        </el-input>
        <!-- <Popover
          placement="bottom"
          width="150"
          trigger="click"
          >
          <div class="chat-list-add-popover">
            <span @click="isEncrypt = false, isGroup = true, changeInitiateCharVisible(true)"><img src="../assets/picture/发起群聊@2x.png" />发起群聊</span>
            <span @click="isEncrypt = true, isGroup = false, changeInitiateCharVisible(true)"><img src="../assets/picture/发起加密聊天@2x.png" />发起加密聊天</span>
            <span @click="isEncrypt = true, isGroup = true, changeInitiateCharVisible(true)"><img src="../assets/picture/发起加密群聊@2x.png" />发起加密群聊</span>
          </div>
          <i slot="reference" class="tico tico-circle-plus-b chat-list__title__add" />
        </Popover>-->
      </div>
      <ChatList
        :chatList="searchCharLisht"
        v-show="chatListVisible"
        class="chat-list__list"
      />
      <FriendListPanel
        v-show="!chatListVisible"
        class="chat-list__friendlist"
        :friendList="friendList"
      />
      <!-- <GroupListPanel :groupList="groupList" />-->
    </div>
    <transition-group name="list">
      <MemberInfo key="1" v-if="chatPanelType === 'member'" class="chat" />
      <DefaultPanel key="2" v-if="chatPanelType === 'default'" class="chat" />
      <ChatPanel key="3" v-show="chatPanelType === 'chat'" class="chat" />
      <InitiateChar
        key="4"
        :visible="initiateCharVisible"
        :friendList="friendList"
        :isEncrypt="isEncrypt"
        :isGroup="isGroup"
        @changeInitiateCharVisible="changeInitiateCharVisible"
      />
      <NotificationPanel
        key="5"
        :visible="notificationVisible"
        @closeVisible="notificationVisible = false"
      />
      <Feedback
        key="6"
        :visible="feedbackVisible"
        @closeVisible="feedbackVisible = false"
      />
    </transition-group>
  </div>
</template>
<script>
//js组件
import { getStorage } from '../js/utils.js'
import BigNumber from 'bignumber.js'
//页面组件
import {
  ChatList,
  ChatPanel,
  DefaultPanel,
  Feedback,
  FriendListPanel,
  InitiateChar,
  MemberInfo,
  NotificationPanel
} from '../components/home'
//socket接口
import { openChatSocket } from '../api/ChatSocket'
// import { createSocket, closeSocket } from '../api/WebSocket'
//业务接口
import { FriendList } from '../api/Friend.js'
import { GetSingleOfflineList } from '../api/Single.js'
import { GetGroupOfflineList, GroupList, GroupListByRoomId } from '../api/Group.js'
//全局地址配置
import apiUrl from '../js/apiUrl'
//状态管理
import { mapState } from 'vuex'
import _ from 'lodash'
//禁言名称数组
import { forbiddenWordsArr } from '../utils/staticName.js'

export default {
  components: {
    DefaultPanel,
    InitiateChar,
    NotificationPanel,
    Feedback,
    ChatList,
    FriendListPanel,
    MemberInfo,
    ChatPanel
  },
  computed: {
    ...mapState('app', [
      'selectMember',
      'chatRoomInfo',
      'chatPanelType',
      'chatListVisible',
      'chatList',
      'unreadList',
      'roomId',
      'friendList',
      'groupList',
      'offLineList'
    ]),
    // 当前用户性别
    sex: function () {
      return getStorage('aillo_sex') * 1
    },
    // 当前用户账号
    userNumber: function () {
      return `${getStorage('aillo_dialCode')}${getStorage('aillo_mobile')}`
    },
    // 当前用户地区
    userRegion: function () {
      return getStorage('aillo_region') === 'null' ? '' : getStorage('aillo_region')
    },
    // 当前用户uid
    uId: function () {
      return getStorage('aillo_uid')
    },
    token: function () {
      return sessionStorage.getItem('aillo_token') + ''
    },
    // 当前总未读信息数
    uneradNum: function () {
      const temp = Object.values(this.unreadList)
      let number = 0
      for (let i = 0; i < temp.length; i++) {
        number += temp[i]
      }
      if (number > 99) {
        number = '99+'
      }
      return number
    },
    // 聊天室小红点样式
    chatIcon: function () {
      return !this.chatListVisible && { opacity: 0.5 }
    },
    // 联系人小红点样式
    userIcon: function () {
      return this.chatListVisible && { opacity: 0.5 }
    },
    // 查询，排序后的聊天室列表
    searchCharLisht: function () {
      const _chatList = []
      if (this.search === '') { // 如果不搜索，将所有聊天室根据最后一条信息时间排序
        _.forIn(this.chatList, (value, key) => {
          // 文件助手
          if (this.selectfileHelper.roomId + '' === key) {
            _chatList.push({
              id: key,
              chatList: value,
              info: this.selectfileHelper
            })
          } else {
            const j = _.findIndex(this.friendList, e => e.roomId + '' === key)
            const k = _.findIndex(this.groupList, e => e.roomId + '' === key)
            if (j !== -1) {
              _chatList.push({
                id: key,
                chatList: value,
                info: this.friendList[j]
              })
            } else if (k !== -1) {
              _chatList.push({
                id: key,
                chatList: value,
                info: this.groupList[k]
              })
            } else {
              _chatList.push({
                id: key,
                chatList: value,
                info: {
                  name: '未知',
                  avatar: '',
                  isEncryptGroup: value.msgType === '"groupChat"'
                }
              })
            }
          }
        })
        const __chatList = _chatList.sort(this.compare())
        return __chatList
      }
      // 如果有搜索，排除不符合要求的聊天室后排序
      const temp = []
      for (let i = 0; i < this.groupList.length; i++) {
        if (RegExp(this.search).test(this.groupList[i].name)) {
          temp.push(this.groupList[i])
        }
      }
      for (let i = 0; i < temp.length; i++) {
        if (!_.isUndefined(this.chatList[temp[i].roomId + ''])) {
          const index = _.findIndex(
            this.groupList,
            e => e.roomId + '' === temp[i].roomId + ''
          )
          if (index !== -1) {
            _chatList.push({
              id: temp[i].roomId + '',
              chatList: this.chatList[temp[i].roomId + ''],
              info: this.groupList[index]
            })
          }
        }
      }
      const _temp = []
      for (let i = 0; i < this.friendList.length; i++) {
        if (RegExp(this.search).test(this.friendList[i].name)) {
          _temp.push(this.friendList[i])
        }
      }
      for (let i = 0; i < _temp.length; i++) {
        if (!_.isUndefined(this.chatList[_temp[i].roomId + ''])) {
          const index = _.findIndex(
            this.friendList,
            e => e.roomId + '' === _temp[i].roomId + ''
          )
          if (index !== -1) {
            _chatList.push({
              id: _temp[i].roomId + '',
              chatList: this.chatList[_temp[i].roomId + ''],
              info: this.friendList[index]
            })
          }
        }
      }
      const __chatList = _chatList.sort(this.compare())
      return __chatList
    }
  },
  data: function () {
    return {
      loading: true,
      // 用户名
      username: getStorage('aillo_name'),
      // 头像
      avatar: getStorage('aillo_avatar'),
      // 签名
      introduce: getStorage('aillo_introduce'),
      // // 好友列表
      // friendList: [],
      // // 群聊列表
      // groupList: [],
      // 当前选择的好友id
      chooseId: null,
      // 当前选择的好友聊天房间id
      chooseRoomId: null,
      // 输入的内容
      inputMsg: '',
      search: '',
      // 发起对话的窗口
      initiateCharVisible: false,
      // 是否加密
      isEncrypt: false,
      // 是否群聊
      isGroup: false,
      notificationVisible: false,
      feedbackVisible: false,
      groupName: null,
      selectfileHelper: { roomId: '100008', name: '文件传输助手', nickName: '文件传输助手', avatar: require('../assets/picture/fileAssistant@2x.png'), friendType: 'fileFriend', id: sessionStorage.getItem('aillo_id') }
    }
  },
  // 初始化ws
  created: function () {
    this.initData()
  },
  methods: {
    // 调用api请求初始化数据
    initData: function () {
      Promise.all(
        [this.getFriendList(), this.getGroupList()]
      ).then(result => {
        this.loading = false
        openChatSocket.setSocketUrl(apiUrl.webws + this.token)
        openChatSocket.createWebSocket(this.chatSocketReceivedHandler)
        // 拉取单聊离线
        this.getSingleOfflineList()
        // 拉取群聊离线列表
        this.getGroupOfflineList()
      })
    },
    // 聊天室排序的方法
    compare () {
      return function (m, n) {
        if (m.chatList.length === 0 || n.chatList.length === 0) {
          return -1
        }
        return (n.chatList[n.chatList.length - 1].timestamp - m.chatList[m.chatList.length - 1].timestamp)
      }
    },
    // 退出登录
    logOut () {
      sessionStorage.clear()
      // closeSocket()
      if (openChatSocket.ws) {
        openChatSocket.ws.close('1000', 'Normal Closure')
      }
      this.$nextTick(() => {
        location.reload()
      })
      this.$router.push({ path: '/login' })
    },
    // 邀请成员入群
    invitMembers (data, subType) {
      const that = this
      that.groupList.map(t => {
        if (t.roomId + '' === data.roomId + '') {
          data.subType = subType
          data.membersNew = data.members.map(e => {
            return e.name
          })
          // that.chatList[t.roomId] = [...that.chatList[t.roomId], data]
          // // 设置聊天列表
          // this.$store.dispatch('app/setChatList', that.chatList)
          // 聊天室信息
          that.chatRoomInfo[t.roomId].data = [...that.chatRoomInfo[t.roomId].data, data]
          this.$store.dispatch('app/setChatRoomInfo', that.chatRoomInfo)
        }
      })
    },
    // 群成员更新
    markRemoveChatRoomInfo (roomId, id) {
      const temp = _.cloneDeep(this.chatRoomInfo)
      // _.remove(temp[data.roomId].data, e => e.userId + '' === data.sender + '')
      const obj = temp[roomId].data.find(e => e.userId + '' === id + '')
      if (obj) {
        obj.delFlag = true
        this.$store.dispatch('app/updateGroupMember', { roomId, data: obj })
        // this.$store.dispatch('app/setChatRoomInfo', temp)
      }
    },
    // 群详情中保存群状态，5+1（群禁言，群解散，退出群，移出群，群封禁）（正常）
    groupStatusMarker (roomId, marker) {
      const _groupList = [...this.groupList]
      const obj = _groupList.find(i => i.roomId === roomId)
      if (obj) {
        obj.groupState = marker
        this.$store.commit('app/GROUPLIST', _groupList)
      }
    },
    // 群详情中保存群状态，5+1（群禁言，群解散，退出群，移出群，群封禁）（正常）
    // 退出群，移出群，针对个人 => 我出群，移除列表；别人退群，更新群成员
    // 群禁言，个人或者群体（群体排除群主和管理员）=> 个人，判断是不是我；群体，判断我是普通成员
    // 群解散,针对群体
    // 群封禁，不收到消息通知
    groupStatusHandle (data) {
      const myId = sessionStorage.getItem('aillo_id')
      const { subType, roomId, userIds } = data
      const addMsgSystemArr = ['addAdmin', 'removeAdmin', 'delGroupMember', 'exitGroup']
      if (addMsgSystemArr.includes(subType) || forbiddenWordsArr.includes(subType)) { this.$store.dispatch('app/addChatListMsg', data) }
      switch (subType) {
        case 'exitGroup':
          const { operInfo } = data
          this.markRemoveChatRoomInfo(roomId, operInfo.userId)
          if (operInfo.userId.includes(myId)) {
            const _groupList = _.cloneDeep(this.groupList)
            _.remove(_groupList, e => e.roomId === roomId)
            this.$store.dispatch('app/setGroupList', _groupList)
            // const _chatList = _.cloneDeep(this.chatList)
            // delete _chatList[roomId]
            // this.$store.dispatch('app/setChatList', _chatList)
            this.$store.dispatch('app/removeChatList', roomId)
            this.$store.commit('app/CHATPANELTYPE', { payload: 'default' })
            this.$store.commit('app/DELETEUNERADLISTNUM', roomId)
          }
          break
        case 'delGroupMember':
          userIds.map(i => {
            this.markRemoveChatRoomInfo(roomId, i)
          })
          if (userIds.includes(myId)) { this.groupStatusMarker(roomId, 'delGroupMember') }
          break
        case 'dissolved':
          this.$store.dispatch('app/updateChatList', { roomId, data: [data] })
          this.groupStatusMarker(roomId, 'dissolved')
          break
        case 'addUser':
          this.groupFriendsJoin(data)
          break
        case 'create':
          this.iJoinGroupChat(data)
          break
        case 'addAdmin':
          this.adminSet(data)
          break
        case 'removeAdmin':
          this.adminSet(data)
          break
      }

      if (forbiddenWordsArr.includes(subType)) {
        const myGroupInfo = this.chatRoomInfo[roomId].data.find(i => i.userId + '' === myId)
        if (myGroupInfo && myGroupInfo.adminType === 0) {
          switch (subType) {
            case 'openGroupForbidSpeak':
              this.groupStatusMarker(roomId, 'openGroupForbidSpeak'); break
            case 'closeGroupForbidSpeak':
              this.groupStatusMarker(roomId, ''); break
            case 'openUserForbidSpeak':
              this.groupStatusMarker(roomId, 'openUserForbidSpeak'); break
            case 'closeUserForbidSpeak':
              this.groupStatusMarker(roomId, ''); break
          }
        }
      }
    },
    /** 新建群聊，我进群聊步骤
     *  1、移除群旧详情数据，拉取群详情新数据；
     *  2、插入群成员数据的房间空数据
     *  3、插入聊天消息
    */
    async iJoinGroupChat (data) {
      const { roomId } = data
      const groupInforRes = await GroupListByRoomId(roomId)
      groupInforRes.data.roomId = groupInforRes.data.id + ''
      this.$store.dispatch('app/addGroupList', { roomId, data: groupInforRes.data })
      this.$store.dispatch('app/addChatRoomInfo', { roomId, data: { data: [] } })
      this.$store.dispatch('app/addChatListMsg', data)
    },

    // 群好友加入
    // 别人入群，群成员信息插入
    // 自己入群，执行iJoinGroupChat
    groupFriendsJoin (data) {
      const { roomId, members, userIds } = data
      const myId = sessionStorage.getItem('aillo_id')
      if (userIds.includes(myId)) {
        this.iJoinGroupChat(data)
      } else {
        this.$store.dispatch('app/addChatListMsg', data)
        const _data = [...this.chatRoomInfo[roomId].data]
        members.map(i => {
          const obj = _data.find(j => j.userId + '' === i.userId + '')
          if (obj) {
            this.$store.dispatch('app/updateGroupMember', { roomId, data: { ...obj, delFlag: false } })
          } else {
            const member = {
              adminType: 9,
              avatar: i.avatar,
              delFlag: false,
              forbidSpeakFlag: false,
              name: i.name,
              nickName: '',
              roomId: Object,
              sex: 0,
              uid: '801137',
              userId: i.userId
            }
            this.$store.dispatch('app/addGroupMember', { roomId, data: member })
          }
        })
        // this.$store.commit('app/addGroupMember', { roomId, data: { data: _data } })
      }
    },
    // 添加和移除管理员
    adminSet (data) {
      const { roomId, members, subType } = data
      const _data = [...this.chatRoomInfo[roomId].data]
      members.map(i => {
        const obj = _data.find(j => j.userId + '' === i.userId + '')
        if (obj) {
          obj.adminType = subType === 'addAdmin' ? 1 : 0
          this.$store.dispatch('app/updateGroupMember', { roomId, data: obj })
        }
      })
    },
    // 删除好友
    // delFriendListFn () {
    //   const that = this
    //   // const ailloName = getStorage('aillo_name') ? getStorage('aillo_name') : getStorage('aillo_mobile')
    //   that.getFriendList()
    //   that.getGroupList()
    // },
    // // 添加好友
    // addNewFriendFn (data) {
    //   const that = this
    //   that.getFriendList()
    // },
    async chatSocketReceivedHandler (res) {
      const that = this
      const myId = sessionStorage.getItem('aillo_id')
      if (res.msgType === 'systemNotice') { // 收到退出登录时的操作
        if (res.subType === 'accountExit') {
          that.$nextTick(() => {
            that.logOut()
          })
          return
        }
      }
      let temp = _.cloneDeep(res)
      const { msgType, subType } = temp

      // 收到单聊或者群聊信息（在线）
      if (msgType === 'groupChat' || msgType === 'singleChat' || msgType === 'fileHelper') {
        // if (msgType === 'singleChat' && receipt) {
        //   // 修改为单聊已接收
        //   const res2 = UpdateSingleReceiver({
        //     token: this.token,
        //     ids: [
        //       temp.data.messageId
        //     ]
        //   })
        // }
        // if (msgType === 'groupChat' && receipt) {
        //   // 修改为单聊已接收
        //   const res2 = UpdateGroupReceiver({
        //     token: this.token,
        //     ids: [
        //       temp.data.messageId
        //     ]
        //   })
        // }
        const { data } = temp
        const _temp = { ...data, ...temp, unread: true }
        delete _temp.data
        if (temp.msgType === 'fileHelper') {
          _temp.isMe = true
          _temp.roomId = '100008'
        }

        // at
        if (temp.subType === 'at') {
          if (temp.data.roomId !== that.roomId) {
            const atArr = temp.data.atModelList
            const atMeObj = atArr.find(i => i.userId === myId)

            if (atMeObj) {
              const parame = {
                roomId: temp.data.roomId,
                someoneAtMe: true
              }
              that.$store.commit('app/SETCHATLISTBASE', parame)
            }
          }
          that.$store.dispatch('app/addChatListMsg', _temp)
          return
        }

        const index = _.findIndex(that.chatList[temp.data.roomId], e => e.messageId === temp.data.messageId)

        if (temp.subType === 'recall' && index !== -1) {
          const payload = { ...temp.data, roomId: _temp.roomId + '', num: 1, subType: 'recall' }
          that.$store.dispatch('app/updateChatListMsg', payload)
          that.$store.commit('app/UPDATEUNREAD', payload)
          return
        }

        if (index === -1) {
          that.$store.dispatch('app/addChatListMsg', _temp)
          if (temp.data.roomId !== that.roomId) { // 如果当前页面聊天室，不是收到消息的这个聊天室，那么未读数据+1
            that.$store.dispatch('app/addUnreadList', { roomId: temp.data.roomId, num: 1 })
          }
        }
      }
      // 群系统消息
      if (msgType === 'groupSystem') {
        const groupSystemArr = ['create', 'addUser', 'addAdmin', 'removeAdmin', 'delGroupMember', 'exitGroup', 'dissolved']
        if (groupSystemArr.includes(subType)) {
          const data = { ...temp.data, msgType, subType }
          that.groupStatusHandle(data)
        }
        // 群禁言
        if (forbiddenWordsArr.includes(subType)) {
          const data = { ...temp.data, msgType, subType }
          that.groupStatusHandle(data)
        }
        // 群封禁 (不走socket通知)
        // 发送消息的时候，提示封禁
        if (subType === 'GROUP_BANNED' || subType === 'GROUP_UNABLE_TO_SEND_MESSAGE') {
          const data = { ...temp.data, msgType, subType }
          that.$store.dispatch('app/updateChatListMsg', data)
          if (subType === 'GROUP_BANNED') {
            that.$store.dispatch('app/addChatListMsg', data)
          }
        }
      }
      // 删除好友、添加好友
      if (temp.msgType === 'systemNotice') {
        if (temp.subType === 'deleteFriend') {
          // that.delFriendListFn()
        }
        if (temp.subType === 'addNewFriend') {
          // const data = JSONbig.parse(temp.data).data
          // that.addNewFriendFn(data)
        }
      }
      if (temp.msgType === 'msgSync') { // 同步app的聊天信息
        if (temp.subType === 'recall') {
          that.$store.commit('app/WITHDRAWCHATLIST', temp.data)
        } else {
          const _temp = temp.data
          const { data } = _temp
          // 同步消息subType设置
          const __temp = { ...data, ..._temp }
          let index
          if (__temp.roomId in that.chatList) {
            index = -1
          } else {
            index = _.findIndex(that.chatList[__temp.roomId], e => !_.isUndefined(e.backId) && e.backId === __temp.backId)
          }
          if (index !== -1) {
            return
          }
          delete __temp.data
          __temp.isMe = true
          __temp.subType = temp.subType
          __temp.msgType = temp.msgType
          // 把数据整理为可以存入聊天列表的结构
          // if (_.isUndefined(that.chatList[temp.data.roomId])) { // 如果聊天列表没有这个聊天室的记录
          //   that.getFriendList()
          //   that.getGroupList()
          //   const res = await getChatRoomInfo(temp.data.roomId) // 获取聊天室信息
          //   that.$store.dispatch('app/addChatRoomInfo', { roomId: temp.data.roomId, data: res }) // 存入聊天室列表
          // }
          const _index = _.findIndex(that.chatList[temp.data.roomId], e => e.backId === temp.data.backId)
          if (_index === -1) {
            that.$store.dispatch('app/addChatListMsg', __temp) // 把聊天信息存入聊天列表
          }
        }
      }
      if (temp.msgType === 'status') {
        if (temp.subType === 'SUCCESS' && temp.data.type !== 'withdraw') {
          const data = { ...temp.data, msgType, subType }
          that.$store.dispatch('app/updateChatListMsg', data)
        }
        if (temp.subType === 'ERROR' && temp.data.backId) { // 被拉黑
          const data = { ...temp.data, msgType, subType }
          that.$store.dispatch('app/updateChatListMsg', data)
          const promptMessage = {
            msgType: 'status',
            subType: 'bePulledBlack',
            roomId: temp.data.roomId,
            timestamp: BigNumber(new Date().getTime()).toString()
          }
          that.$store.dispatch('app/addChatListMsg', promptMessage)
        }
      }
    },

    // 选中联系人发起聊天的方法
    changeInitiateCharVisible (e) {
      this.initiateCharVisible = e
    },
    // 切换聊天室页面，联系人页面，默认页面的方法
    changeChatListVisible (e) {
      this.$store.dispatch('app/setChatListVisible', e)
      if (e) {
        this.$store.dispatch('app/setChatPanelType', 'member')
      } else {
        this.$store.dispatch('app/setChatPanelType', 'default')
      }
    },
    // 好友列表
    getFriendList: function () {
      return new Promise(async (resolve, reject) => {
        const res = await FriendList({
          token: this.token
        })
        if(res.status == 401){
          this.$message.error('账号密码错误')
        }else if (res.status !== 200) {
          this.$message.error('请求接口异常')
        }
        // // 文件助手file transfer
        // const fileTransfer = { avatar: '', nickName: '文件传输助手', name: '文件传输助手', roomId: '100008', friendType: 'fileFriend', id: sessionStorage.getItem('aillo_id') }
        // const t = [...res.data, { ...fileTransfer }]
        // console.log('t', t)
        this.$store.dispatch('app/setFriendList', res.data)
        for (let i = 0; i < res.data.length; i++) {
          this.$store.dispatch('app/addUnreadList', { roomId: res.data[i].roomId + '', num: 0 }) // 添加未读信息
        }
        resolve()
      })
    },

    // 接收离线单聊消息
    getSingleOfflineList: async function () {
      const res = await GetSingleOfflineList({
        token: this.token
      })
      if (res.data.length === 0) return
      res.data.forEach((item) => {
        const supportedMsgTypes = [
          'text', 'image', 'file', 'video', 'audio'
        ]
        if (!supportedMsgTypes.includes(item.subType)) return

        this.chatSocketReceivedHandler(item, false)
      })
    },
    // 接收离线群聊消息
    getGroupOfflineList: async function () {
      const res = await GetGroupOfflineList({
        token: this.token
      })
      if (res.data.length === 0) return
      res.data.forEach((item) => {
        const supportedMsgTypes = [
          'text', 'image', 'file', 'video', 'audio'
        ]
        if (!supportedMsgTypes.includes(item.subType)) return

        this.chatSocketReceivedHandler(item, false)
      })
    },
    // 群聊列表
    getGroupList: function () {
      // const myId = sessionStorage.getItem('aillo_id')
      return new Promise(async (resolve, reject) => {
        const res = await GroupList({
          token: this.token
        })
        if(res.status == 401){
          this.$message.error('账号密码错误')
        }else if (res.status !== 200) {
          this.$message.error('账号密码错误')
        }
        const _groupList = res.data
        let _chatRoomInfo = {}
        _groupList.map(i => {
          this.$store.dispatch('app/addUnreadList', { roomId: i.roomId + '', num: 0 }) // 添加未读信息
          _chatRoomInfo[i.roomId + ''] = { data: [] }
        })
        this.$store.dispatch('app/initGroup', _chatRoomInfo)

        // getAllGroupChatRoomInfo().then(res => { // 群成员数据的请求和处理
        //   const { data } = res
        //   let _chatRoomInfo = {}
        //   for (let i = 0; i < data.length; i++) {
        //     const temp = []
        //     for (let j = 0; j < data[i].groupMemberListModels.length; j++) {
        //       temp.push(data[i].groupMemberListModels[j])
        //     }
        //     _chatRoomInfo[data[i].groupMemberListModels[0].roomId + ''] = { data: temp }
        //   }
        //   // 遍历，禁言设置
        //   _groupList.map(g => {
        //     const menberMe = _chatRoomInfo[g.roomId].data.find(m => m.userId + '' === myId)
        //     // if顺序不可替换，个人禁言优先级更大
        //     if (g.forbidSpeakFlag) {
        //       if (menberMe.adminType === 0) g.groupState = 'openUserForbidSpeak'
        //     }
        //     if (menberMe && menberMe.forbidSpeakFlag) {
        //       g.groupState = 'openUserForbidSpeak'
        //     }
        //   })

        //   this.$store.commit('app/CHATROOMINFO', _chatRoomInfo)
        //   // this.loading = false
        // })
        this.$store.dispatch('app/setGroupList', _groupList)
        resolve()
      })
    }
  },
  destroyed () {
    if (openChatSocket.ws) {
      openChatSocket.ws.close('1000', 'Normal Closure')
    }
  }
}
</script>

<style lang="scss">
body {
  background: #666666;
}
sup {
  transform: translateY(-50%) translateX(73%) !important;
}
.list-enter-active,
.list-leave-active {
  transition: all 0.2s;
}
.list-enter,
.list-leave-to {
  opacity: 0;
}
.aillo-home {
  position: absolute;
  top: calc(50% - 316px);
  left: calc(50% - 445px);
  right: 0;
  bottom: 0;
  width: 900px;
  height: 623px;
  background: rgba(255, 255, 255, 1);
  border-radius: 9px;

  /* 好友列表*/
  .chat-list {
    position: absolute;
    left: 61px;
    width: 288px;
    height: 623px;
    background: rgba(255, 255, 255, 1);
    .el-input__prefix {
      top: 7px !important;
    }
    .el-input__inner {
      border-radius: 20px;
      background-color: #f5f5f5;
      height: 30px;
    }
    .el-input__suffix {
      top: -5px !important;
    }
    &__friendlist {
      left: 0px;
      width: 100%;
      height: calc(100% - 52px);
      overflow-y: auto;
    }
    &__list {
      left: 0px;
      width: 100%;
      height: calc(100% - 52px);
      overflow-y: auto;
    }
    &__title {
      height: 51px;
      background: rgba(255, 255, 255, 1);
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 16px;
      border-bottom: 1px solid #eee;
      border-right: 1px solid #eee;
      &__search {
        width: 206px;
        img {
          cursor: pointer;
        }
      }
      &__add {
        font-size: 33px;
        color: #3478f5;
        cursor: pointer;
      }
    }
  }

  .chat {
    position: absolute;
    left: 349px;
    width: 550px;
    height: 623px;
  }

  /* 左边菜单栏*/
  .menu {
    position: absolute;
    width: 61px;
    height: 623px;
    background: #3478f5;
    border-radius: 9px 0px 0px 9px;
    &__title {
      width: 60px;
      height: 52px;
      background: #3478f5;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 9px 0px 0px 0px;
      &__avatar {
        width: 35px;
        height: 35px;
        border-radius: 100px;
        background-color: white;
      }
    }
    &__chat {
      position: relative;
      left: calc(50% - 11px);
      top: 47px;
      font-size: 10px;
      &__icon {
        font-size: 24px;
        cursor: pointer;
        color: white;
        cursor: pointer;
      }
    }
    &__user {
      position: relative;
      left: calc(50% - 35px);
      top: 100px;
      &__icon {
        font-size: 22px;
        cursor: pointer;
      }
    }
    &__setting {
      cursor: pointer;
      position: absolute;
      bottom: 34px;
      width: 24px;
      left: calc(50% - 12px);
    }
  }
}
.user-info-card {
  display: flex;
  padding: 0 15px;
  &__avatar {
    width: 47px;
    height: 47px;
    margin-right: 16px;
    border-radius: 100px;
    background-color: white;
  }
  &__info {
    margin-bottom: 16px;
    display: flex;
    flex-direction: column;
    width: 180px;
    &__name {
      font-weight: 500;
      font-size: 19px;
      margin-right: 7px;
      margin-bottom: 16px;
    }
    &__female {
      font-size: 11px;
      color: #ff6379;
    }
    &__male {
      font-size: 11px;
      color: #508aff;
    }
    &__account {
      font-size: 14px;
      font-weight: 400;
      color: #666;
      margin-bottom: 7px;
      color: rgba(102, 102, 102, 1);
    }
    &__district {
      font-size: 14px;
      font-weight: 400;
      font-weight: 400;
      color: #666;
    }
  }
}
.chat-list-setting-popover {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin: -12px -7px;
  cursor: pointer;
  span {
    height: 50px;
    width: 100%;
    display: flex;
    align-items: center;
    padding-left: 11px;
    font-weight: 400;
    font-size: 18px;
    &:hover {
      background-color: #f5f5f5;
    }
  }
}
.chat-list-add-popover {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin: -12px;
  span {
    font-size: 16px;
    font-weight: 400;
    height: 50px;
    width: 100%;
    display: flex;
    align-items: center;
    user-select: none;
    cursor: pointer;
    &:hover {
      background-color: #f5f5f5;
    }
    img {
      margin-left: 10px;
      width: 17px;
      height: 17px;
      margin-right: 7px;
      margin-bottom: -2px;
    }
  }
}
</style>
